﻿using System;
using System.Collections.Generic;
using System.Drawing;

namespace PTop.Code.LngLat
{
    public class LngLatHelper
    {
        private const double EARTH_RADIUS = 6378.137;//地球半径
        private static double rad(double d)
        {
            return d * Math.PI / 180.0;
        }

        /// <summary>
        /// 获取两个位置的距离/km
        /// </summary>
        /// <param name="lat1"></param>
        /// <param name="lng1"></param>
        /// <param name="lat2"></param>
        /// <param name="lng2"></param>
        /// <returns></returns>
        public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
        {
            double radLat1 = rad(lat1);
            double radLat2 = rad(lat2);
            double a = radLat1 - radLat2;
            double b = rad(lng1) - rad(lng2);

            double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
             Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
            s = s * EARTH_RADIUS;
            s = Math.Round(s * 10000) / 10000;
            return s;
        }

        /// <summary>
        /// lat,lng队列的距离/km
        /// </summary>
        /// <param name="latLngs"></param>
        /// <returns></returns>
        public static double GetDistance(List<double[]> latLngs)
        {
            double d = 0;
            for (var i = 1; i < latLngs.Count; i++)
            {
                var p1 = latLngs[i - 1];
                var p2 = latLngs[i];
                var dTemp = GetDistance(p1[0], p1[1], p2[0], p2[1]);
                d += dTemp;
            }
            return d;
        }

        /// <summary>
        /// 获取拐角距离/km
        /// </summary>
        /// <param name="lat1"></param>
        /// <param name="lng1"></param>
        /// <param name="lat2"></param>
        /// <param name="lng2"></param>
        /// <returns></returns>
        public static double GetCornerDistance(double lat1, double lng1, double lat2, double lng2)
        {
            var s1 = GetDistance(lat1, lng1, lat1, lng2);
            var s2 = GetDistance(lat1, lng2, lat2, lng2);
            var s = s1 + s2;
            return s;
        }

        /// <summary>
        /// 百度坐标系转换为火星坐标系
        /// </summary>
        /// <param name="bdLat">百度纬度</param>
        /// <param name="bdLng">百度经度</param>
        /// <returns>{ ggLat, ggLon }</returns>
        public static double[] BdToGcj02(double bdLat, double bdLng)
        {
            double x = bdLng - 0.0065, y = bdLat - 0.006;
            double z = Math.Sqrt(x * x + y * y) - 0.00002 * Math.Sin(y * Math.PI);
            double theta = Math.Atan2(y, x) - 0.000003 * Math.Cos(x * Math.PI);
            var ggLon = z * Math.Cos(theta);
            var ggLat = z * Math.Sin(theta);
            return new[] { ggLat, ggLon };
        }
    }
}
